#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/3/29 11:40
# @Author : 闫峰
# @File    : shop.py
import time

import requests

from third_services.shopee.base_tool import shop_auth, db, shop_auth_shop
from third_services.shopee.common.common_func import get_timestamp, get_access_token, get_shop_id
from utils.otherutils.json_format import json_format


class Interface_shop:
    base_url = "https://partner.shopeemobile.com"
    timestamp = int(time.time())
    partner_id = 2001656

    def api_v2_product_get_item_base_info(self, ordersourceid, item_id_list,
                                          apiService="/api/v2/product/get_item_base_info"):
        """使用此api可以逐项获取item_id列表的基本信息。"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "item_id_list": item_id_list,
            "need_complaint_policy": True,
            "need_tax_info": True
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "item_id_list": item_id_list,
                    "need_complaint_policy": True,
                    "need_tax_info": True
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_product_get_item_extra_info(self, ordersourceid, item_id_list,
                                           apiService="/api/v2/product/get_item_extra_info"):
        """使用此api可以获取逐项列表的额外信息。"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "item_id_list": item_id_list,
            "need_complaint_policy": 1,
            "need_tax_info": 1
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()
        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "item_id_list": item_id_list,
                    "need_complaint_policy": 1,
                    "need_tax_info": 1
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_product_get_model_list(self, ordersourceid, item_id, apiService="/api/v2/product/get_model_list"):
        """获取项目的模型列表。"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "item_id": item_id
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "item_id": item_id
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_product_get_item_promotion(self, ordersourceid, item_id_list,
                                          apiService="/api/v2/product/get_item_promotion"):
        """获获取商品促销信息。"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "item_id_list": item_id_list
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "item_id_list": item_id_list
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_product_get_category(self, ordersourceid, apiService="/api/v2/product/get_category"):

        """获取类别树数据。更多细节请查看https://open.shopee.com/developer-guide/209"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_bundle_deal_get_bundle_deal(self, ordersourceid, bundle_deal_id,
                                           apiService="/api/v2/bundle_deal/get_bundle_deal"):

        """获取捆绑交易详细信息"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "bundle_deal_id": bundle_deal_id
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "bundle_deal_id": bundle_deal_id
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response

    def api_v2_product_get_item_list(self, ordersourceid, offset, apiService="/api/v2/product/get_item_list"):
        """获取捆绑交易详细信息"""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "offset": offset,
            "page_size": 100,
            "item_status": "NORMAL"

        }
        try:
            response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                        allow_redirects=False, timeout=30).json()
        except requests.exceptions.Timeout as e:
            print('API request timed out:', e)
            response = {'request_id': '53e6a387a78432a282f02ca16a15bd20', 'error': 'API request timed out',
                        'message': 'This app type has no permission to this API.'}
            return response
        count = 0
        while True:
            if count < 10000:
                if response['error'] == 'error_sign':
                    param = {
                        "partner_id": self.partner_id,
                        "timestamp": get_timestamp(),
                        "access_token": get_access_token(ordersourceid),
                        "sign": shop_auth_shop(ordersourceid, apiService),
                        "shop_id": get_shop_id(ordersourceid),
                        "offset": offset,
                        "page_size": 100,
                        "item_status": "NORMAL"

                    }
                    try:
                        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                                    allow_redirects=False, timeout=30).json()
                    except requests.exceptions.Timeout as e:
                        print('API request timed out:', e)
                        response = {'request_id': '53e6a387a78432a282f02ca16a15bd20', 'error': 'API request timed out',
                                    'message': 'This app type has no permission to this API.'}
                else:
                    return response
            else:
                response = {'request_id': '53e6a387a78432a282f02ca16a15bd20', 'error': 'qingqiu10000ci',
                            'message': 'This app type has no permission to this API.'}
                return response

    def api_v2_product_update_item(self, ordersourceid, apiService="/api/v2/product/update_item"):
        """支持更新：标题/描述/预购信息/上下架"""
        sign = shop_auth_shop(ordersourceid, apiService)
        sql1 = """	SELECT CertIdAccessKeyId,UserTokenSecretAccessKey  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.fetch_all(sql1, (ordersourceid,))
        access_token = res1[0]["UserTokenSecretAccessKey"]
        shop_id = res1[0]["CertIdAccessKeyId"]
        url = self.base_url + apiService
        payload = {

            "pre_order": {
                "is_pre_order": False,
                "days_to_ship": 10
            },
            "item_id": 23578685837

        }
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "shop_id": shop_id
        }
        response = requests.request("POST", url, headers=headers, json=payload, params=param,
                                    allow_redirects=False).json()

        return response


    def get_item_limit(self, ordersourceid,
                                           apiService="/api/v2/product/get_item_limit"):

        """Get item upload control."""
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": int(get_shop_id(ordersourceid))
        }
        response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()

        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid)
                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response


if __name__ == '__main__':
    # 产品基本信息
    # res = Interface_shop().api_v2_product_get_item_base_info(13682, 22954809049)
    res = Interface_shop().get_item_limit(13674)
    # 产品额外信息
    # res = Interface_shop().api_v2_product_get_item_extra_info(14143, 23854429617)
    # 变体产品根据平台item_id 得到 model_id
    # res = Interface_shop().api_v2_product_get_model_list(14143, 23854429617)
    # 根据来源渠道id 获得类目
    # res = Interface_shop().api_v2_product_get_category(13531,14397034667)
    # 根据渠道id 平台id 获得产品的促销信息
    # res = Interface_shop().api_v2_product_get_item_promotion(15101,18156063195)
    # res = Interface_shop().api_v2_product_update_item(16843)
    # res = Interface_shop().api_v2_product_update_item(14267)
    # res = Interface_shop().api_v2_product_update_item(13998)
    print(json_format(res))
